$(document).ready(function () {
  let rows = 30;
  let cells = 50;

  for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
    let rowDiv = $("<div>");
    rowDiv.addClass("rowDiv");
    for (let cellIndex = 0; cellIndex < cells; cellIndex++) {
      let cellDiv = $("<div>");
      cellDiv.css({
        "height": "20px",
        "width": "20px",
        "border": "1px #000000 solid",
        "background-color": "#rgb(192, 230, 255)"
      });

      cellDiv.addClass("row_" + rowIndex);
      cellDiv.addClass("cell_" + cellIndex);

      rowDiv.append(cellDiv);
    }
    $("#plate").append(rowDiv);
  }

  let player = {
    nikeName: "巨蟒",
    speed: 500,
    head: "R",
    position: [
      {
        x: 29, y: 0
      },
      {
        x: 29, y: 1
      },
      {
        x: 29, y: 2
      },
    ],
    color: "00ff00"
  };

  // 初始化蛇的初始位置
  player.position.forEach(p => {
    $(".row_" + p.x + ".cell_" + p.y).css("background-color", "#" + player.color);
  });

  function move() {
    setTimeout(() => {
      let headCellIndex = player.position[player.position.length - 1];

      let nextCellIndex;
      switch (player.head) {
        case "U":
          nextCellIndex = {
            x: headCellIndex.x - 1,
            y: headCellIndex.y
          };
          break;
        case "R":
          nextCellIndex = {
            x: headCellIndex.x,
            y: headCellIndex.y + 1
          };
          break;
        case "D":
          nextCellIndex = {
            x: headCellIndex.x + 1,
            y: headCellIndex.y
          };
          break;
        case "L":
          nextCellIndex = {
            x: headCellIndex.x,
            y: headCellIndex.y - 1
          };
          break;
      }

      // 检测是否越界
      if (nextCellIndex.x < 0 || nextCellIndex.x >= rows ||
        nextCellIndex.y < 0 || nextCellIndex.y >= cells) {
        alert("游戏结束");
        return;
      }

      // 检测是否吃到食物
      let foodIndex = SystemConfig.foods.findIndex(f => f.x === nextCellIndex.x && f.y === nextCellIndex.y);
      if (foodIndex !== -1) {
        player.position.push(nextCellIndex);
        // 移除食物
        SystemConfig.foods.splice(foodIndex, 1);
        // 更新食物显示
        $(".row_" + nextCellIndex.x + ".cell_" + nextCellIndex.y).css("background-color", "#" + player.color);
      } else {
        player.position.push(nextCellIndex);
        let lastIndex = player.position.splice(0, 1);
        $(".row_" + nextCellIndex.x + ".cell_" + nextCellIndex.y).css("background-color", "#" + player.color);
        $(".row_" + lastIndex[0].x + ".cell_" + lastIndex[0].y).css("background-color", "");
      }

      move();
    }, player.speed);
  }

  move();

  // 控制蛇的方向
  $("body").keydown(function (e) {
    switch (e.keyCode) {
      case 37: // 左
        if (player.head === "R") 
        return;
        player.head = "L";
        break;
      case 38: // 上
        if (player.head === "D") 
        return;
        player.head = "U";
        break;
      case 39: // 右
        if (player.head === "L") 
        return;
        player.head = "R";
        break;
      case 40: // 下
        if (player.head === "U") 
        return;
        player.head = "D";
        break;
    }
  });

  // 速度随时间变快
  setInterval(() => {
    player.speed -= 50;
    player.speed = Math.max(player.speed, 50);
  }, 0.1 * 60 * 1000);

  let SystemConfig = {
    putFoodTime: 2 * 1000,
    putFoodCount: 2,
    Color: "1b1b1b",
    foods: []
  };

  // 生成食物
  setInterval(() => {
    let PutFood = () => {
      let newFood = {
        x: Math.floor(Math.random() * rows),
        y: Math.floor(Math.random() * cells)
      };

      let hasFoods = SystemConfig.foods.some(s => s.x === newFood.x && s.y === newFood.y);
      if (hasFoods) {
        // 如果食物位置重合，则重新生成食物
        PutFood();
      } else {
        SystemConfig.foods.push(newFood);
        let foodCell = $(".row_" + newFood.x + ".cell_" + newFood.y);
        foodCell.css({
          "background-color": "#" + SystemConfig.Color
        });
      }
    };

    for (let i = 0; i < SystemConfig.putFoodCount; i++) {
      PutFood();
    }
  }, SystemConfig.putFoodTime);
});
